package com.cuitrip.business.order;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.app.rong.RongTitleTagHelper;
import com.cuitrip.business.conversation.rong.RongMessageProxy;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.order.detail.OrderFormActivity;
import com.cuitrip.business.order.model.ConversationOrderItem;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.order.ui.InsiderOrderConversationHolderView;
import com.cuitrip.business.order.ui.TravellerOrderConversationHolderView;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.adapter.HolderViewAdapter;
import com.lab.app.BaseFragment;
import com.lab.jumper.Jumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.ArrayUtil;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * Created on 7/18.
 */
public class OrderConversationListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = "OrderConversationListFragment";

    public static final int DEFAULT_SIZE = 200;
    public static final String KEY_HAS_UNREAD_MESSAGE = "has_unread_message";

    public static final int TYPE_TRAVEL = 0;
    public static final int TYPE_FINDER = 1;
    public static final String TYPE = "order_type";

    private View mContentView;
    private List<ConversationOrderItem> mOrderList = new ArrayList<>();
    private List<ConversationOrderItem> mRightBarList = new ArrayList<>();

    @Bind(R.id.ct_list)
    ListView mListView;

    @Bind(R.id.ct_swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @Bind(R.id.state_layout)
    StateLayout mStateLayout;
    ImageView imageBackgroundView;
    @Bind(R.id.top_bar)
    View topBar;


    @Bind(R.id.bar_left_item)
    IconTextView leftItem;

    @Bind(R.id.bar_right_item)
    TextView rightItem;

    @Bind(R.id.bar_middle_item)
    TextView middleItem;

    @Bind(R.id.right_red_point)
    View mRedRightPoint;

    private HolderViewAdapter mAdapter;

    protected int mType = TYPE_TRAVEL;

    private boolean isHistory = false;//是否历史预约

    private int nowUnreadCount = 0;

    private int historyUnreadCount = 0;


    public void gotoTab() {
        IndexActivity.gotoTab(getHostActivity(), IndexActivity.RECOMMEND_TAB_INDEX);
    }

    public void setHistory(boolean isHistory) {
        this.isHistory = isHistory;
    }


    public static OrderConversationListFragment newInstance(int type) {
        OrderConversationListFragment fragment = new OrderConversationListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter filter = new IntentFilter(OrderItem.ORDER_STATUS_CHANGED_ACTION);
        filter.addAction(RongMessageProxy.NEW_MESSAGE_RECEIVED);
        getHostActivity().registerReceiver(mOrderStatusChangedReceiver, filter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mContentView == null) {
            mContentView = inflater.inflate(R.layout.ct_order_ist, null);
        }

        ButterKnife.bind(this, mContentView);
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        if (userInfo != null && !userInfo.isTravel() && imageBackgroundView!=null) {
            imageBackgroundView.setImageResource(R.drawable.insiders_null_bg);
        }
        return mContentView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTitle();
        initView();
        initData();
        initListener();
        updateStateLayout();
    }

    private void initData() {
        mContentView.post(new Runnable() {
            @Override
            public void run() {
                if (LoginInstance.getInstance().isLogin()) {
                    getCurrentOrderList();
                }
            }
        });
    }

    private void updateStateLayout() {
        mStateLayout.setAction(new StateLayout.Action() {
            @Override
            public void performEmptyAction() {
                gotoTab();
            }
        });
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        if (LoginInstance.isLogin() &&
                !userInfo.isTravel()) {
            mStateLayout.setEmptyLogoRes(R.drawable.trip_yy_bx);
            mStateLayout.setEmptyContentRes(R.string.book_blank_desc_fi);
            mStateLayout.setEmptyTitleRes(R.string.main_nav_redervation);
            mStateLayout.hideAction();
        } else {
            mStateLayout.setEmptyLogoRes(R.drawable.trip_xl_bx);
            mStateLayout.setEmptyContentRes(R.string.book_blank_desc_ft);
            mStateLayout.setEmptyTitleRes(R.string.main_nav_book);
            mStateLayout.showAction();
        }
        mStateLayout.setEmptyLayoutID(
                ((userInfo!=null&&userInfo.isTravel()==false)?
                        R.layout.home_empty_insider_layout:R.layout.home_empty_layout));
    }

    private void initTitle() {
        topBar.setBackgroundColor(getResources().getColor(R.color.ct_white));
        middleItem.setTextColor(getResources().getColor(R.color.ct_black));
        if (isHistory) {
            middleItem.setText(getString(R.string.book_histroy));
            leftItem.setText(getString(R.string.back_icon));
            leftItem.setTextColor(ResourceUtil.getThemeColor());
            leftItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().finish();
                }
            });
        } else {
            rightItem.setText(getString(R.string.book_histroy));
            rightItem.setTextColor(ResourceUtil.getThemeColor());
            rightItem.setVisibility(View.GONE);
            if (LoginInstance.getInstance().isLogin() && !LoginInstance.getInstance().getUserInfo().isTravel()) {
                middleItem.setText(getString(R.string.booking));
            } else {
                middleItem.setText(getString(R.string.booking));
            }
            rightItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Jumper.launchActivity(getActivity(), new Intent(getActivity(), HistoryOrderListActivity.class));
                }
            });
        }
    }


    public void onDestroy() {
        super.onDestroy();
        getHostActivity().unregisterReceiver(mOrderStatusChangedReceiver);
    }

    public void onResume() {
        super.onResume();
        if (LoginInstance.getInstance().isLogin()) {
            topBar.setVisibility(View.VISIBLE);
            if (!mOrderList.isEmpty()){
                fetchRong(mOrderList, false);
            }
            if (isHistory){
                if (LoginInstance.getInstance().getUserInfo().isTravel()){
                    TrackUtil.trackScreenName("/booking/list/history");
                }else{
                    TrackUtil.trackScreenName("/insider/booking/list/history");
                }
            }else{
                if (LoginInstance.getInstance().getUserInfo().isTravel()){
                    TrackUtil.trackScreenName("/insider/booking/list");
                }else{
                    TrackUtil.trackScreenName("/booking/list");
                }
            }


        } else {
            topBar.setVisibility(View.GONE);
            mStateLayout.changeState(StateLayout.State.Empty);
        }
    }


    private void initView() {
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        if (userInfo != null) {
            if (LoginInstance.getInstance().getUserInfo().isTravel()) {
                mType = TYPE_TRAVEL;
                mAdapter = new HolderViewAdapter(getActivity(), mOrderList, TravellerOrderConversationHolderView.class);
            } else {
                mType = TYPE_FINDER;
                mAdapter = new HolderViewAdapter(getActivity(), mOrderList, InsiderOrderConversationHolderView.class);
            }
            mListView.setAdapter(mAdapter);
        }
    }

    private void initListener() {
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Object item = adapterView.getAdapter().getItem(i);
                if (item instanceof ConversationOrderItem) {
                    ConversationOrderItem orderItem = (ConversationOrderItem) item;
                    if (orderItem.getUnreadCount() > 0) {
                        // OrderFormActivity.startConversation(getActivity(), ((ConversationOrderItem) item).getOid());
                        OrderFormActivity.startConversation(getActivity(), ((ConversationOrderItem) item).getOid());
                    } else {
                        OrderFormActivity.start(getActivity(), ((ConversationOrderItem) item).getOid());
                        //OrderFormActivity.start(getActivity(), (ConversationOrderItem) item);

                    }
                }
            }
        });

        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                getCurrentOrderList();
            }
        });
    }

    protected void onLoginSuccess() {
//        mNoLogin.setVisibility(View.GONE);
    }

    private void fetchRong(List<ConversationOrderItem> conversationOrderItemList, boolean isNotifyRightBar) {
        new RequestRongTask(conversationOrderItemList, isNotifyRightBar).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    private void inflateList(List<ConversationOrderItem> orderList) {
        mOrderList.clear();
        mOrderList.addAll(orderList);
    }

    private void inflateRightList(List<ConversationOrderItem> orderList) {
        mRightBarList.clear();
        mRightBarList.addAll(orderList);
    }

    private void getCurrentOrderList() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(true);
            ApiProxy apiProxy = new ApiProxy(new IProxyCallback() {
                @Override
                public boolean onProxyResult(ProxyResult<?> result) {
                    if (mSwipeRefreshLayout != null) {
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                    CtApiResponse response = (CtApiResponse) result.getData();
                    if (!isAdded()) {
                        return false;
                    }
                    if (response != null && response.isResponseNormal()) {
                        if (response.result instanceof List) {
                            List<ConversationOrderItem> orderItemList = (List<ConversationOrderItem>) response.result;
                            if (ArrayUtil.isNullOrEmpty(orderItemList)) {
                                mStateLayout.changeState(StateLayout.State.Empty);
                                fetchRightBarList();
                            } else {
                                inflateList(orderItemList);
                                fetchRong(orderItemList, false);
                                mStateLayout.changeState(StateLayout.State.INIT);
                            }
                        }
                    } else {
                        if (response != null && !TextUtils.isEmpty(response.msg)) {
                            MessageUtils.showToast(response.msg);
                        }
                        if (mStateLayout != null) {
                            mStateLayout.changeState(StateLayout.State.NoNetwork);
                        }

                    }
                    return false;
                }
            });
            OrderBusiness.getOrderList(apiProxy, mType, 0, DEFAULT_SIZE, isHistory);
        }
    }

    /**
     * 获取右上角的红点请求
     */
    private void fetchRightBarList() {
        ApiProxy mRightBarProxy = new ApiProxy(new IProxyCallback() {
            @Override
            public boolean onProxyResult(ProxyResult<?> result) {
                CtApiResponse response = (CtApiResponse) result.getData();
                if (!isAdded()) {
                    return false;
                }
                if (response != null && response.isResponseNormal()) {
                    if (response.result instanceof List) {
                        List<ConversationOrderItem> orderItemList = (List<ConversationOrderItem>) response.result;
                        inflateRightList(orderItemList);
                        if (ArrayUtil.isNullOrEmpty(orderItemList)) {
                            rightItem.setVisibility(View.GONE);
                        } else {
                            rightItem.setVisibility(View.VISIBLE);
                            fetchRong(orderItemList, true);
                        }
                    }
                }
                return false;
            }
        });
        OrderBusiness.getOrderList(mRightBarProxy, mType, 0, DEFAULT_SIZE, true);
    }

    public void addConversationAttributes(Conversation conversation, ConversationOrderItem item) {
        item.setId(conversation.getTargetId());
        item.setUnreadCount(conversation.getUnreadMessageCount());
        item.setTime(String.valueOf(RongTitleTagHelper.buildDateString(conversation.getSentTime())));
        item.setLast(conversation.getSentTime());
//        item.setLastWords(RongCloudEvent.getMessageContent(conversation.getLatestMessage()));
    }


    public class RequestRongTask extends AsyncTask<Void, Void, Boolean> {

                private List<ConversationOrderItem> list;
        private boolean notifyTopBar;
        private int noticeCount;

        public RequestRongTask(List<ConversationOrderItem> list, boolean notifyTopBar) {
            this.list = list;
            this.notifyTopBar = notifyTopBar;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                final CountDownLatch countDownLatch = new CountDownLatch(1);
                if (RongIM.getInstance() != null && RongIM.getInstance().getRongIMClient() != null) {
                    RongIM.getInstance().getRongIMClient().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
                        @Override
                        public void onSuccess(final List<Conversation> conversations) {
                            if (conversations == null) {
                                LogHelper.e(TAG, "empty conversation");
                            } else {
                                for (ConversationOrderItem orderItem : list) {
                                    for (Conversation conversation : conversations) {
                                        if (conversation.getTargetId().equals(orderItem.getTargetId())) {
                                            noticeCount = noticeCount + conversation.getUnreadMessageCount();
                                            addConversationAttributes(conversation, orderItem);
                                        }

                                    }
                                }
                            }

                            countDownLatch.countDown();
                        }


                        public void onError(RongIMClient.ErrorCode errorCode) {

                            countDownLatch.countDown();
                        }

                    }, Conversation.ConversationType.DISCUSSION);
                }
                countDownLatch.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Boolean value) {
            super.onPostExecute(value);
            if (!isAdded()) {
                return;
            }
            //非历史预约界面发出统计
            if (!isHistory) {
                if (notifyTopBar) {
                    mRedRightPoint.setVisibility(noticeCount > 0 ? View.VISIBLE : View.INVISIBLE);
                    historyUnreadCount = noticeCount;

                    Intent intent = new Intent(OrderItem.MESSAGE_UNREAD_COUNT_CHANGED_ACTION);
                    intent.putExtra(KEY_HAS_UNREAD_MESSAGE, nowUnreadCount + historyUnreadCount > 0);

                    LocalBroadcastManager.getInstance(AppCoreRuntime.context).sendBroadcast(intent
                    );
                    return;
                } else {
                    nowUnreadCount = noticeCount;
                    //没进入历史预约，才需要历史预约的红点
                    fetchRightBarList();
                }
            }
            mAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onRefresh() {
        getCurrentOrderList();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    private ConversationHandler mConversationHandler = new ConversationHandler(this);

    public static class ConversationHandler extends Handler {

        public static final int REFRESH_CURRENT_LIST = 0x01;
        public static final int REFRESH_RONG_MESSAGE_LIST = 0x02;
        public static final int REFRESH_RONG_RIGHT_MESSAGE_LIST = 0x03;

        WeakReference<OrderConversationListFragment> fragmentReference;

        public ConversationHandler(OrderConversationListFragment conversationListFragment) {
            fragmentReference = new WeakReference<>(conversationListFragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            OrderConversationListFragment orderConversationListFragment;
            if (fragmentReference.get() == null) {
                return;
            }
            orderConversationListFragment = fragmentReference.get();
            switch (msg.what) {
                case REFRESH_CURRENT_LIST:
                    orderConversationListFragment.getCurrentOrderList();
                    break;
                case REFRESH_RONG_MESSAGE_LIST:
                    orderConversationListFragment.fetchRong(orderConversationListFragment.mOrderList, false);
                    break;
                case REFRESH_RONG_RIGHT_MESSAGE_LIST:
                    orderConversationListFragment.fetchRong(orderConversationListFragment.mRightBarList, true);
                    break;
            }
        }
    }

    //新的push广播消息
    private BroadcastReceiver mOrderStatusChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (OrderItem.ORDER_STATUS_CHANGED_ACTION.equals(intent.getAction())) {
                mConversationHandler.removeMessages(ConversationHandler.REFRESH_CURRENT_LIST);
                mConversationHandler.sendEmptyMessage(ConversationHandler.REFRESH_CURRENT_LIST);
            } else if (RongMessageProxy.NEW_MESSAGE_RECEIVED.equals(intent.getAction())) {
                mConversationHandler.removeMessages(ConversationHandler.REFRESH_RONG_MESSAGE_LIST);
                mConversationHandler.sendEmptyMessage(ConversationHandler.REFRESH_RONG_MESSAGE_LIST);
                mConversationHandler.removeMessages(ConversationHandler.REFRESH_RONG_RIGHT_MESSAGE_LIST);
                mConversationHandler.sendEmptyMessageDelayed(ConversationHandler.REFRESH_RONG_RIGHT_MESSAGE_LIST, 2000);
            }
        }
    };

}
